package com.hxrd.androidprint.fragment;


import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hxrd.androidprint.DBUtils.DBUtils;
import com.hxrd.androidprint.FileOperator;
import com.hxrd.androidprint.R;
import com.hxrd.androidprint.UrlPath;
import com.hxrd.androidprint.WarehouseSendGoodsActivity;
import com.hxrd.androidprint.adapter.GoodsNameAdapter;
import com.hxrd.androidprint.bean.DetailBean;
import com.hxrd.androidprint.bean.PrintBean;
import com.hxrd.androidprint.bean.ScanCodeBean;
import com.hxrd.androidprint.utils.T;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import hardware.print.printer;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by Administrator on 2017/11/2.
 */

public class SendForthFragment extends Fragment implements WarehouseSendGoodsActivity.CallBackForth{

    private String name;

    //设置上传文件的格式
    // private static final MediaType MEDIA_TYPE_TXT = MediaType.parse("text/x-markdown; charset=utf-8");

    private TextView tvSendGoodsCode, tvGoodsName, tvPlanSendGoodsCount, tvScanSendGoodsCount, tvBoxCode;
    private EditText etCarName;
    private Button btnClear, btnUpload, btnNoCode, btnExit;
    private RelativeLayout backLayout;
    private List<DetailBean> detailBeanListQuery = new ArrayList<>();
    private List<DetailBean> detailBeanList = new ArrayList<>();
    private ListView goodsNameListView;
    private GoodsNameAdapter goodsNameAdapter;
    private DetailBean detailBean;
    // private boolean firstScan=true,firstDialog=true;
    private String ERP_Product_Code = "ERP_Product_Code=";
    private String qrCode = "&qrCode=";
    private String types = "&types=";
    private String type = "1";
    // private int boxScancount=0;
    // private int scanCount1=0;
    printer m_printer = new printer();
    private String failMsg;

    private String urlIp;


    //设置上传文件的格式
    private static final MediaType MEDIA_TYPE_TXT = MediaType.parse("text/x-markdown; charset=utf-8");
    private File fileName;
    //控制是否显示未满48小时的弹出框
    boolean isShow = true;

    //更新数据弹出框
    private ProgressDialog progressdialog;

    List<DetailBean> detailUpDataList;
    List<PrintBean> printList;
    List<ScanCodeBean> codeUpDataList;

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 3) {// 发货单号网络错误
                tvSendGoodsCode.setText("");
                Toast.makeText(getActivity(), "网络错误！", Toast.LENGTH_SHORT).show();
                // firstScan=true;
            } else if (message.what == 2) {
                tvSendGoodsCode.setText("");
                Toast.makeText(getActivity(), "发货单号错误！", Toast.LENGTH_SHORT).show();
                // firstScan=true;
            } else if (message.what == 1) {

                String scanCode = message.obj.toString();

                String state=DBUtils.querySendGoodsState(getActivity(),scanCode);

                if(state!=null&&state.equals("1")){
                    Toast.makeText(getActivity(),"该发货单号已经扫描，请勿重复扫描！",Toast.LENGTH_SHORT).show();
                    tvSendGoodsCode.setText("");
                }else{
                    tvSendGoodsCode.setText(scanCode);
                    if (DBUtils.querySendGoodsCodeByOrderCode(getActivity(), scanCode).size() > 0) {
                        //tvSendGoodsCode.setText(scanCode);
                        // 退出程序再次进入后，该码存在，只能扫一次，修改状态
                        DBUtils.updateSendGoodsStateByOrderCode(getActivity(),scanCode,"1");
                    }else{
                        DBUtils.insertSendGoodsCode(getActivity(), scanCode);
                    }

                    detailBeanListQuery = DBUtils.queryDetailByOrderCode(getActivity(), scanCode);
                    if (detailBeanListQuery.size() > 0) {
                        tvSendGoodsCode.setText(scanCode);
                    } else {
                        for (int i = 0; i < detailBeanList.size(); i++) {
                            DBUtils.insertDetail(getActivity(), scanCode, detailBeanList.get(i).getWMSD_Code(), detailBeanList.get(i).getERP_DCode(),
                                    detailBeanList.get(i).getShipper_Code(), detailBeanList.get(i).getShip_Code(), detailBeanList.get(i).getERP_Product_Code(),
                                    detailBeanList.get(i).getProduct_Name(), detailBeanList.get(i).getPack_QTY() + "", detailBeanList.get(i).getFactoryName(),
                                    detailBeanList.get(i).getWareHouse_Code(), "0", detailBeanList.get(i).getPlan_Outbound_Time(), "0");
                            DBUtils.insertPrint(getActivity(), detailBeanList.get(i).getWMSD_Code(), detailBeanList.get(i).getProduct_Name(), "0", "0", name,
                                    scanCode, etCarName.getText().toString().trim(), detailBeanList.get(i).getERP_DCode(), detailBeanList.get(i).getERP_Product_Code());
                        }
                        detailBeanListQuery = DBUtils.queryDetailByOrderCode(getActivity(), scanCode);
                    }
                }

                /*detailBeanListQuery = DBUtils.queryDetailByOrderCode(getActivity(), scanCode);
                if (detailBeanListQuery.size() > 0) {
                    tvSendGoodsCode.setText(scanCode);
                } else {
                    for (int i = 0; i < detailBeanList.size(); i++) {
                        DBUtils.insertDetail(getActivity(), scanCode, detailBeanList.get(i).getWMSD_Code(), detailBeanList.get(i).getERP_DCode(),
                                detailBeanList.get(i).getShipper_Code(), detailBeanList.get(i).getShip_Code(), detailBeanList.get(i).getERP_Product_Code(),
                                detailBeanList.get(i).getProduct_Name(), detailBeanList.get(i).getPack_QTY() + "", detailBeanList.get(i).getFactoryName(),
                                detailBeanList.get(i).getWareHouse_Code(), "0", detailBeanList.get(i).getPlan_Outbound_Time(), "0");
                        DBUtils.insertPrint(getActivity(), detailBeanList.get(i).getWMSD_Code(), detailBeanList.get(i).getProduct_Name(), "0", "0", name,
                                scanCode, etCarName.getText().toString().trim(), detailBeanList.get(i).getERP_DCode(), detailBeanList.get(i).getERP_Product_Code());
                    }
                    detailBeanListQuery = DBUtils.queryDetailByOrderCode(getActivity(), scanCode);
                }*/

            } else if (message.what == 4) {// 箱码网络错误
                Toast.makeText(getActivity(), "网络错误！", Toast.LENGTH_SHORT).show();
                //  firstScan=false;
            } else if (message.what == 5) {

                String noQuating = message.obj.toString().split("\"")[1];

                String[] result = noQuating.split(";");
                Log.e("WarehouseSendGoodsActiv", message.obj.toString());
                double goodsCount = Double.valueOf(result[1]);
                String backCode = result[2];
                Log.e("后台返回的码", backCode);
                String str = tvPlanSendGoodsCount.getText().toString().trim();
                // String str1=str.substring(0,str.indexOf("."));
                double planCount = Double.valueOf(str);
                double scanCount = Double.valueOf(tvScanSendGoodsCount.getText().toString().trim());

                double count = planCount - scanCount;
                if (count < goodsCount) {
                    //Toast.makeText(WarehouseSendGoodsActivity.this,"按剁扫已超出计划数量",Toast.LENGTH_SHORT).show();
                    type = "2";
                    if (planCount == scanCount) {
                        Toast.makeText(getActivity(), "该产品已经扫描完成", Toast.LENGTH_SHORT).show();
                    } else {

                        goodsCountDialog(planCount - scanCount, backCode);

                    }

                } else {

                    type = "1";
                    if (DBUtils.queryBackCode(getActivity(), backCode).size() > 0) {
                        Toast.makeText(getActivity(), "该码已经扫描过，请勿重复扫码。", Toast.LENGTH_SHORT).show();
                    } else {

                        DBUtils.insertScanCode(getActivity(), tvSendGoodsCode.getText().toString().trim(), etCarName.getText().toString().trim(),
                                detailBean.getWMSD_Code(), detailBean.getERP_Product_Code(), backCode, goodsCount + "", type, detailBean.getIs_has_code());
                        //垛箱数
                        scanCount = scanCount + goodsCount;
                        tvScanSendGoodsCount.setText(scanCount + "");
                        DBUtils.changeScanCount(getActivity(), detailBean.getWMSD_Code(), tvScanSendGoodsCount.getText().toString().trim());
                        String saveDuoCount = DBUtils.queryPrintDuoCount(getActivity(), detailBean.getWMSD_Code());
                        double hasDuoCount = 0;
                        if (saveDuoCount != null) {
                            hasDuoCount = Double.valueOf(saveDuoCount) + goodsCount;
                        }
                        DBUtils.updatePrintDuoCount(getActivity(), detailBean.getWMSD_Code(), hasDuoCount + "");
                        if (scanCount == detailBean.getPack_QTY()) {
                            handler.sendEmptyMessage(7);
                        }


                        type = "1";
                    }

                }
                //这个里面判断满48小时的正确码
            } else if (message.what == 6) {
                type = "1";

                String result = message.obj.toString().split(";")[1];
                if (message.obj.toString().split(";").length == 4) {
                    if (isShow == true) {


                        message.obj = message.obj.toString().replace("false;生产时间不足48小时", "true");
                        unFullTimeDialog(message.obj.toString());
                    } else {
                        message.obj = message.obj.toString().replace("false;生产时间不足48小时", "true");
                        Message message1 = Message.obtain();
                        message1.obj = message.obj;
                        message1.what = 5;
                        handler.sendMessage(message1);
                    }

                } else {
                    Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();


                }
            }
            if (message.what == 7) {
                //处理该产品是否扫面完成

                finishDialog();
            }
            if (message.what == 8) {


                progressdialog.dismiss();

                initPrint();
                Toast.makeText(getActivity(), "数据上传完成。", Toast.LENGTH_SHORT).show();

                tvSendGoodsCode.setText("");
                tvGoodsName.setText("");
                tvPlanSendGoodsCount.setText("0");
                tvScanSendGoodsCount.setText("0");
                tvBoxCode.setText("");
                detailBeanList.clear();
                etCarName.setText("");

            }
            if (message.what == 9) {
                progressdialog.dismiss();
                tvSendGoodsCode.setText("");
                tvGoodsName.setText("");
                tvPlanSendGoodsCount.setText("0");
                tvScanSendGoodsCount.setText("0");
                tvBoxCode.setText("");
                detailBeanList.clear();
                etCarName.setText("");
                Toast.makeText(getActivity(), failMsg, Toast.LENGTH_SHORT).show();

            }
            return false;
        }
    });
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_send_goods_page_four, null);

        WarehouseSendGoodsActivity activity = (WarehouseSendGoodsActivity) getActivity();
        activity.getData(this);

        Bundle bundle=getArguments();
        name=bundle.getString("name");
        urlIp=bundle.getString("urlIp");
        Log.e("-------fragment4",name+urlIp);

        tvSendGoodsCode = (TextView) view.findViewById(R.id.tv_send_goods_code);
        tvGoodsName = (TextView) view.findViewById(R.id.tv_goods_name);
        tvPlanSendGoodsCount = (TextView) view.findViewById(R.id.tv_plan_send_goods_count);
        tvScanSendGoodsCount = (TextView) view.findViewById(R.id.tv_scan_send_goods_count);
        tvBoxCode = (TextView) view.findViewById(R.id.tv_box_code);
        etCarName = (EditText) view.findViewById(R.id.et_car_name);
        backLayout = (RelativeLayout) view.findViewById(R.id.main_list_back_layout);
        btnClear = (Button) view.findViewById(R.id.btn_clear);
        btnUpload = (Button) view.findViewById(R.id.btn_upload);
        btnNoCode = (Button) view.findViewById(R.id.btn_no_code);
        btnExit = (Button) view.findViewById(R.id.btn_exit);

        m_printer.Open();
        m_printer.SetGrayLevel((byte) 6);

        tvGoodsName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!TextUtils.isEmpty(etCarName.getText().toString())) {
//                    startActivity(new Intent(WarehouseSendGoodsActivity.this,ListActivity.class));
                    if (TextUtils.isEmpty(tvSendGoodsCode.getText().toString().trim())) {
                        Toast.makeText(getActivity(), "请先扫描发货单号", Toast.LENGTH_SHORT).show();
                    } else {
                        detailBeanListQuery = DBUtils.queryDetailByOrderCode(getActivity(), tvSendGoodsCode.getText().toString());
                        if(detailBeanListQuery.size()!=0){
                            final Dialog scanModeDialog = new Dialog(getActivity());
                            //绑定弹出框布局,
                            View viewDialog = LayoutInflater.from(getActivity()).inflate(R.layout.goods_name_dialog_view, null);
                            goodsNameListView = (ListView) viewDialog.findViewById(R.id.scan_mode_dialog_list_view);

                            scanModeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                            scanModeDialog.setContentView(viewDialog);
                            //detailBeanListQuery = DBUtils.queryDetail(WarehouseSendGoodsActivity.this);
                            goodsNameAdapter = new GoodsNameAdapter(getActivity(), detailBeanListQuery);
                            goodsNameListView.setAdapter(goodsNameAdapter);
                            //goodsNameListView.notifyDataSetChanged();

                            // 显示
                            scanModeDialog.show();


                            goodsNameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @SuppressLint("ResourceAsColor")
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                                    detailBean = detailBeanListQuery.get(position);
                                    String scanCount = DBUtils.queryDetailScanCount(getActivity(), detailBean.getWMSD_Code());

                                    if (scanCount != null) {
                                        tvScanSendGoodsCount.setText(scanCount);
                                    }
                                    tvGoodsName.setText(detailBean.getProduct_Name());
                                    tvPlanSendGoodsCount.setText(detailBean.getPack_QTY() + "");
                                    if(detailBean.getIs_has_code().equals("1")){
                                        btnNoCode.setText("有码发货");

                                    }else {
                                        btnNoCode.setText("无码发货");
                                    }
                                    //  firstDialog=true;
                                    scanModeDialog.dismiss();
                                }
                            });
                        }else {
                            Toast.makeText(getActivity(), "请稍等，正在获取发货单信息", Toast.LENGTH_SHORT).show();
                        }

                    }
                } else {
                    Toast.makeText(getActivity(), "请先输入叉车司机。", Toast.LENGTH_SHORT).show();
                }

            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String scanCode=tvSendGoodsCode.getText().toString().trim();

                if(scanCode!=null){
                    // 点击清空，恢复状态
                    DBUtils.updateSendGoodsStateByOrderCode(getActivity(),scanCode,"0");
                }

                tvSendGoodsCode.setText("");
                tvGoodsName.setText("");
                tvPlanSendGoodsCount.setText("0");
                tvScanSendGoodsCount.setText("0");
                tvBoxCode.setText("");
                detailBeanList.clear();
                etCarName.setText("");
            }
        });

        btnNoCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (detailBean != null) {

                    noCodeDialog(btnNoCode.getText().toString().trim());


                } else {
                    Toast.makeText(getActivity(), "请先选择产品。", Toast.LENGTH_SHORT).show();
                }

            }
        });
        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopDialog();
            }
        });

        backLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopDialog();
            }
        });

        btnUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (!TextUtils.isEmpty(tvSendGoodsCode.getText().toString().trim())) {


                    dataUpDialog();
                    //initPrint();

                } else {
                    Toast.makeText(getActivity(), "请先扫描发货单号。", Toast.LENGTH_SHORT).show();
                }

                //initPrint();

            }
        });


        return view;
    }

    private void initUpData() {
        progressdialog = ProgressDialog.show(getActivity(), "请等待...", "正在为您上传数据...");
        progressdialog.setCancelable(false);// 设置是否可以通过点击Back键取消

        fileName = new File("/sdcard/DataUp/" + tvSendGoodsCode.getText().toString() + ".txt");

        if (!fileName.exists()) {
            try {
                fileName.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        detailUpDataList = DBUtils.queryDetailByOrderCode(getActivity(), tvSendGoodsCode.getText().toString());
        codeUpDataList = DBUtils.queryScanCodeByOrderCode(getActivity(), tvSendGoodsCode.getText().toString());

        for (int i = 0; i < detailUpDataList.size(); i++) {
            for (int j = 0; j < codeUpDataList.size(); j++) {

                if (detailBeanList.get(i).getWMSD_Code().equals(codeUpDataList.get(j).getWMSD_Code())) {

                    writeTxtToFile(codeUpDataList.get(j).getTypes() + "," + codeUpDataList.get(j).getBackCode() + ","
                                    + codeUpDataList.get(j).getWMSD_Code() + "," + codeUpDataList.get(j).getCodeCount()+"," +codeUpDataList.get(j).getIs_has_code()+ "\r\n",
                            "/sdcard/DataUp/", fileName.getName().toString());
                }
            }
        }
        DBUtils.deleteDetail(getActivity(), tvSendGoodsCode.getText().toString());
        DBUtils.deleteScanCode(getActivity(), tvSendGoodsCode.getText().toString());
        DBUtils.deleteSendGoodsCode(getActivity(), tvSendGoodsCode.getText().toString());

        dataUpUrl();

    }

    private void dataUpUrl() {
        //获取要上传的文件名
        final File file = new File("/sdcard/DataUp/");


        new Thread(new Runnable() {
            @Override
            public void run() {


                OkHttpClient.Builder builder = new OkHttpClient.Builder()
                        .connectTimeout(6000, TimeUnit.SECONDS)
                        .writeTimeout(6000, TimeUnit.SECONDS)
                        .readTimeout(6000, TimeUnit.SECONDS);
                OkHttpClient client = builder.build();


                RequestBody requestBodyPost = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("FileName", fileName.getName().toString())
                        .addFormDataPart("DATA", fileName.getName().toString(), RequestBody.create(MEDIA_TYPE_TXT, new File("/sdcard/DataUp/" + fileName.getName().toString())))
                        .build();


                Log.e("上传文件名", fileName.getName().toString());

                final Request request = new Request.Builder()
                        .header("Authorization", "Client-ID " + "...")
                        .url(urlIp + UrlPath.UP_DATA_DATA + name)
                        .post(requestBodyPost)
                        .build();


                Call call = client.newCall(request);

                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                        handler.sendEmptyMessage(3);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {

                        String upState = response.body().string();
                        Log.e("上传状态", upState);
                        if (upState.contains("true")) {

                            File deleteFile = new File("/sdcard/DataUp/" + fileName.getName().toString());
                            if (deleteFile.exists()) {

                                //把上传完成的文件移动到上传完成的文件夹中
                                FileOperator.moveFile("/sdcard/DataUp/" + fileName.getName().toString(), "/sdcard/HaveDataUp/");
                                deleteFile.delete();
                            }

                                    /*upDataTime++;
                                    if (upDataTime == fileList.length) {

                                        handler.sendEmptyMessage(8);

                                    }*/
                            handler.sendEmptyMessage(8);

                        }
                        if (upState.contains("false")) {
                            failMsg = upState.replace("false;", "");
                            handler.sendEmptyMessage(9);

                                    /*upDataTime++;
                                    if (upDataTime == fileList.length) {

                                        handler.sendEmptyMessage(8);

                                    }*/

                        }


                    }
                });
            }
        }).start();

    }

    // 将字符串写入到文本文件中
    public void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent;
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }

            //这个是续写的方法
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
            //这个是重写的方法
//            FileOutputStream out = null;
//            //重写文件，覆盖掉原来的数据
//            out = new FileOutputStream(file);
//            out.write(strContent.getBytes());
//            out.flush();
//            out.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }


    private void goodsCountDialog(final double boxCount, final String backCode) {
        final Dialog dialog = new Dialog(getActivity());
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.scan_box_code_dialog, null);
        final EditText edBoxCount = (EditText) view.findViewById(R.id.ed_box_count);
        TextView tvBoxCount = (TextView) view.findViewById(R.id.tv_box_count);
        Button btnSure = (Button) view.findViewById(R.id.btn_sure_dialog);

        tvBoxCount.setText("零散箱数不得大于" + boxCount + "箱");

        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(view);
        dialog.setCancelable(false);

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(edBoxCount.getText().toString())) {
                    T.showShort(getActivity(), "请输入零散箱数");
                } else {
                    //输入的散扫数
                    double scanCount1 = Double.valueOf(edBoxCount.getText().toString());
                    if (scanCount1 <= 0) {
                        T.showShort(getActivity(), "零散箱数不得小于0");
                    } else if (scanCount1 > boxCount) {
                        Toast.makeText(getActivity(), "零散箱数大于" + boxCount + "箱，请重新输入", Toast.LENGTH_SHORT).show();
                        // firstDialog=false;
                    } else {
                        // firstDialog=false;
                        if (DBUtils.queryBackCode(getActivity(), backCode).size() > 0) {

                            Toast.makeText(getActivity(), "该码已扫描过，请勿重复扫码", Toast.LENGTH_SHORT).show();

                        } else {
                            DBUtils.insertScanCode(getActivity(), tvSendGoodsCode.getText().toString().trim(), etCarName.getText().toString().trim(),
                                    detailBean.getWMSD_Code(), detailBean.getERP_Product_Code(), backCode, scanCount1 + "", type, detailBean.getIs_has_code());


                            //查询数据库中的散扫数
                            double hasSanCount = Double.valueOf(DBUtils.queryPrintSanCount(getActivity(), detailBean.getWMSD_Code()));

                            //已经扫描的数量
                            double hasScanCount = Double.valueOf(tvScanSendGoodsCount.getText().toString().trim()) + scanCount1;

                            DBUtils.changeScanCount(getActivity(), detailBean.getWMSD_Code(), "" + hasScanCount);
                            tvScanSendGoodsCount.setText(hasScanCount + "");
                            //String saveSanCount = DBUtils.queryPrintSanCount(WarehouseSendGoodsActivity.this, detailBean.getWMSD_Code());

                            hasSanCount = hasSanCount + scanCount1;

                            DBUtils.updatePrintSanCount(getActivity(), detailBean.getWMSD_Code(), "" + hasSanCount);
                            type = "1";
                            if (hasScanCount == detailBean.getPack_QTY()) {
                                handler.sendEmptyMessage(7);
                            }
                        }
                        dialog.dismiss();
                    }
                }


                //finish();
            }
        });

        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }

    @Override
    public void getResult(String result) {
        String scanCode=result;
        if (!TextUtils.isEmpty(scanCode)) {

            if (!TextUtils.isEmpty(etCarName.getText().toString())) {

                if (TextUtils.isEmpty(tvSendGoodsCode.getText().toString().trim())) {// 发货单号

                    //tvSendGoodsCode.setText(scanCode);

                    getDeliveryByCodeUrl(scanCode);

                } else {// 箱码
                    if (!TextUtils.isEmpty(tvGoodsName.getText().toString().trim())) {
                        if (detailBean.getIs_has_code().equals("0")) {
                            if (!Double.valueOf(tvScanSendGoodsCount.getText().toString()).equals(Double.valueOf(tvPlanSendGoodsCount.getText().toString()))) {
                                tvBoxCode.setText(scanCode);
                                checkProductUrl(detailBean.getERP_Product_Code(), scanCode);
                            } else {
                                Toast.makeText(getActivity(), "该产品已扫描完成", Toast.LENGTH_SHORT).show();
                            }
                        } else {
                            Toast.makeText(getActivity(), "该产品已经无码发货。", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        Toast.makeText(getActivity(), "请选择产品名称", Toast.LENGTH_SHORT).show();
                    }
                }
            } else {
                Toast.makeText(getActivity(), "请先输入叉车司机。", Toast.LENGTH_SHORT).show();

            }
        }
    }

    private void getDeliveryByCodeUrl(final String sendGoodsCode) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(urlIp + UrlPath.GET_DELIVERY_BYCODE_URL + sendGoodsCode).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(3);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    if (jsonObject.has("Data")) {
                        JSONArray jsonArray = jsonObject.getJSONArray("Data");
                        if (jsonArray.length() != 0) {
                            detailBeanList = new Gson().fromJson(jsonArray.toString(),
                                    new TypeToken<List<DetailBean>>() {
                                    }.getType());
                            Message message = Message.obtain();
                            message.what = 1;
                            message.obj = sendGoodsCode;
                            handler.sendMessage(message);
                        } else {
                            handler.sendEmptyMessage(2);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void checkProductUrl(final String productCode, final String boxCode) {

        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder().url(urlIp + UrlPath.CHECK_PRODUCT_URL + ERP_Product_Code + productCode
                + qrCode + boxCode).build();

        /*Log.e("-------UrlPath",UrlPath.CHECK_PRODUCT_URL+ ERP_Product_Code+productCode
                +qrCode+boxCode+types+type);*/

        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(4);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Message message = Message.obtain();
                if (result.contains("true")) {
                    message.obj = result;
                    message.what = 5;
                    handler.sendMessage(message);
                    //handler.sendEmptyMessage(5);
                } else if (result.contains("false")) {
                    message.obj = result;
                    message.what = 6;
                    handler.sendMessage(message);
                }
            }
        });
    }

    private void stopDialog() {
        final Dialog dialog = new Dialog(getActivity());
        View dialogView = LayoutInflater.from(getActivity())
                .inflate(R.layout.stop_dialog, null);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure_dialog);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel_dialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(dialogView);
        dialog.setCancelable(false);

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                DBUtils.updateAllSendGoodsState(getActivity());
                getActivity().finish();
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }


    private void dataUpDialog() {
        final Dialog dialog = new Dialog(getActivity());
        View dialogView = LayoutInflater.from(getActivity())
                .inflate(R.layout.data_up_dialog, null);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure_dialog);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel_dialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(dialogView);
        dialog.setCancelable(false);

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                initUpData();


            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }



    private void unFullTimeDialog(final String msg) {
        final Dialog dialog = new Dialog(getActivity());
        View dialogView = LayoutInflater.from(getActivity())
                .inflate(R.layout.unfull_time_dialog, null);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure_dialog);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel_dialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(dialogView);
        dialog.setCancelable(false);

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

                Message message = Message.obtain();
                message.obj = msg;
                message.what = 5;
                isShow = false;
                handler.sendMessage(message);
            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }

    private void finishDialog() {
        final Dialog dialog = new Dialog(getActivity());
        View dialogView = LayoutInflater.from(getActivity())
                .inflate(R.layout.finish_dialog, null);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure_dialog);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(dialogView);
        dialog.setCancelable(false);

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();

                tvGoodsName.setText("");
                tvBoxCode.setText("");
                tvPlanSendGoodsCount.setText("0.0");
                tvScanSendGoodsCount.setText("0.0");


            }
        });

        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }


    private void noCodeDialog(final String title) {
        final Dialog dialog = new Dialog(getActivity());
        View dialogView = LayoutInflater.from(getActivity())
                .inflate(R.layout.delete_file_dialog, null);
        Button btnSure = (Button) dialogView.findViewById(R.id.btn_sure_dialog);
        Button btnCancel = (Button) dialogView.findViewById(R.id.btn_cancel_dialog);
        TextView titleText= (TextView) dialogView.findViewById(R.id.is_has_code_title);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(dialogView);
        dialog.setCancelable(false);
        titleText.setText("确定"+title+"吗？");

        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                if(title.equals("无码发货")){
                    DBUtils.changeIsHasCode(getActivity(), detailBean.getWMSD_Code(), "1");
                    DBUtils.insertScanCode(getActivity(), tvSendGoodsCode.getText().toString().trim(), "", detailBean.getWMSD_Code(), "", "", "", "", "1");
                    btnNoCode.setText("有码发货");
                }else {
                    DBUtils.changeIsHasCode(getActivity(), detailBean.getWMSD_Code(), "0");
                    DBUtils.deleteScanCodeByWMSD_Code(getActivity(),detailBean.getWMSD_Code());
                    DBUtils.changeScanCount(getActivity(), detailBean.getWMSD_Code(), "0");
                    btnNoCode.setText("无码发货");
                }

                dialog.dismiss();


            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });


        dialog.show();
        WindowManager windowManager = getActivity().getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = (int) (display.getWidth()); //设置宽度
        dialog.getWindow().setAttributes(lp);
    }

    private void initPrint() {

        printList = DBUtils.queryPrintByOrderCode(getActivity(), tvSendGoodsCode.getText().toString());

        Log.e("要打印的列表", printList.toString());
        Log.e("要打印的列表大小", "printList.size():" + printList.size());

        String detailCode = printList.get(0).getOrder_Code();

        m_printer.PrintLineInit(50);
        m_printer.PrintLineString("主单单号:   " + detailCode, 20, printer.PrintType.Centering, true);
        m_printer.PrintLineEnd();


        String carName = printList.get(0).getCar_Name();

        m_printer.PrintLineInit(20);
        m_printer.PrintLineString("叉车司机:   " + carName, 20, printer.PrintType.Centering, true);
        m_printer.PrintLineEnd();
        m_printer.PrintLineInit(20);
        m_printer.PrintLineString("发货人:   " + name, 20, printer.PrintType.Centering, true);
        m_printer.PrintLineEnd();



        for (int i = 0; i < printList.size(); i++) {

            String goodsName = printList.get(i).getERP_Product_Code();
            String duoCount = printList.get(i).getDuo_Count();
            String sanCount = printList.get(i).getSan_Count();

            m_printer.PrintLineInit(40);
            m_printer.PrintLineString(goodsName+"/"+duoCount+"/"+sanCount, 20, printer.PrintType.Left, true);
            m_printer.PrintLineEnd();


//            String str = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
//            m_printer.PrintLineInit(30);
//            m_printer.PrintLineString(str, 18, printer.PrintType.Centering, true);
//            m_printer.PrintLineEnd();


        }


        DBUtils.deletePrint(getActivity(), tvSendGoodsCode.getText().toString());
//
//        for (int i = 0; i <5 ; i++) {
//
//            String str = "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~";
//            m_printer.PrintLineInit(18);
//            m_printer.PrintLineString(str, 18, printer.PrintType.Centering, true);
//            m_printer.PrintLineEnd();
//
//            String str1 = "品种:     " + "PET冷充填2.0L百事可乐6入";
//            m_printer.PrintLineInit(50);
//            m_printer.PrintLineString(str1, 20, printer.PrintType.Left, true);
//            m_printer.PrintLineEnd();
//
//            String str2 =  "6入全包（北京普通版）";
//            m_printer.PrintLineInit(20);
//            m_printer.PrintLineString(str2, 20, printer.PrintType.Left, true);
//            m_printer.PrintLineEnd();
//        }


    }

}



